One string is given.
·
If the letter ‘f’ occurs in the string only once, print its index (indexing starts from 0).
·
If the letter ‘f’ occurs two or more times, print the indices of its first and last occurrences.
·
If the letter ‘f’ does not appear in the string, print nothing.
Input. One single string with a length not exceeding 255
characters.
Output. Print the result based on the number of occurrences of the
letter ‘f’ in the string.
Sample input 1 |
Sample output 1 |
comfort |
3 |
|
|
Sample input 2 |
Sample output 2 |
office |
1 2 |
strings
Algorithm
analysis
Count the number of occurrences of the letter ‘f’ in the
string, keeping track of the indices of its first and last appearances.
Algorithm implementation
Read the string character by character until the end (up to
the ‘\n’ character). The index of the current character is
stored in the variable ind. The number of occurrences of the letter ‘f’ is
counted in the variable cnt.
cnt = 0; ind = 0;
while(scanf("%c",&ch),
ch != '\n')
{
The variables f and s store the indices
of the first and last appearances of the letter ‘f’.
if
(ch == 'f')
{
If the letter ‘f’ is encountered and it appears for the first time (the
variable cnt is equal to 0), the current index is assigned to the
variable f.
if
(cnt == 0) f = ind;
The letter ‘f’ is not encountered for the first time (if cnt
> 0). Assign the current index ind to the variable s.
if
(cnt > 0) s = ind;
cnt++;
}
ind++;
}
Print the result
based on the number of occurrences of the letter ‘f’ in the
string.
if (cnt == 1)
printf("%d\n",f);
else
if (cnt > 1)
printf("%d
%d\n",f,s);
Java implementation
import java.util.*;
public class Main
{
public static void
main(String[] args)
{
Scanner con = new
Scanner(System.in);
String str = con.nextLine();
int first = str.indexOf("f");
int last = str.lastIndexOf("f");
if (first != -1)
{
if (first == last) System.out.println(first);
else System.out.println(first + "
" + last);
}
}
}
Python implementation
Read the input string.
s = input()
Find the
indices of the first and last occurrences of the symbol ‘f’.
first_index = s.find('f')
last_index = s.rfind('f')
Print the answer.
if first_index == -1:
The letter ‘f’ does not
occur.
pass
elif first_index == last_index:
The letter ‘f’ occurs
only once.
print(first_index)
else:
The letter ‘f’ occurs
two or more times.
print(first_index, last_index)